package com.heshi.mongo.controller;

import com.alibaba.fastjson.JSONObject;
import com.heshi.mongo.dao.ContactMeRepository;
import com.heshi.mongo.entity.ContactMe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/contactMe")
public class ContactMeController {
    @Autowired
    private ContactMeRepository contactMeRepository;

    @PostMapping("/save")
    public JSONObject save(@RequestBody ContactMe contactMe) {
        JSONObject jsonObject = new JSONObject();
        contactMeRepository.save(contactMe);
        return jsonObject;
    }

    @GetMapping("/getAll")
    public JSONObject getAll() {
        JSONObject jsonObject = new JSONObject();
        List<ContactMe> list = contactMeRepository.findAll();
        jsonObject.put("result", list);
        return jsonObject;
    }

    @GetMapping("/get")
    public JSONObject findByName(String name, @RequestParam(required = false) String email) {
        JSONObject jsonObject = new JSONObject();
        ContactMe contactMe = new ContactMe();
        contactMe.setName(name);
        contactMe.setEmail(email);

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.caseSensitive())
                .withMatcher("email", ExampleMatcher.GenericPropertyMatchers.startsWith());
        Example<ContactMe> example = Example.of(contactMe, matcher);
        Optional<ContactMe> optional = contactMeRepository.findOne(example);
        jsonObject.put("result", optional.isPresent() ? optional.get() : null);
        return jsonObject;
    }
}
